package a10_动态规划;

import java.util.Arrays;

/**
 * <p>
 * a14_最后一块石头的重量2复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/3/20
 */
public class a14_最后一块石头的重量2复习3 {
    //如果能簇成sum/2，说明没有剩下的
    //如果能簇成容量sum/2的最大重量的为dp[target]
    //那么剩下的是sum - dp[target]

    //01背包
    public int lastStoneWeightII(int[] stones) {
        int sum = Arrays.stream(stones).sum();
        int target = sum / 2;

        int[] dp = new int[target+1];
        for (int i = 0; i < stones.length; i++) {
            for (int j = target; j >= stones[i]; j--) {
                dp[j] = Math.max(dp[j],dp[j-stones[i]] + stones[i]);
            }
        }

        return sum - dp[target] - dp[target];
    }
}
